/**
 * 
 */
package com.feib.stms.dao.jdbc;

import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;
import org.springframework.stereotype.Repository;

import com.feib.stms.dao.TempUploadFileErrorDao;
import com.feib.stms.dao.jdbc.rowmapper.TempUploadFileErrorRowMapper;
import com.feib.stms.model.TempUploadFileError;
import com.feib.stms.pagination.PaginatedList;

/**
 * @author Jimmy Liu
 *
 */
@Repository("tempUploadFileErrorDao")
public class TempUploadFileErrorJdbcDao extends BaseJdbcDao implements TempUploadFileErrorDao {

	protected OracleSequenceMaxValueIncrementer sequence;

	protected SimpleJdbcInsert tempUploadFileErrorJdbcInsert;

	@Override
	protected void initDao() throws Exception {
		super.initDao();
		this.sequence = new  OracleSequenceMaxValueIncrementer(this.getDataSource(), "TEMP_UPLOAD_FILE_ERROR_PK_SEQ");
		this.tempUploadFileErrorJdbcInsert = new  SimpleJdbcInsert(this.getDataSource());
		this.tempUploadFileErrorJdbcInsert.withTableName("TEMP_UPLOAD_FILE_ERROR")
		.usingColumns("TEMP_UPLOAD_FILE_ERROR_PK", "TEMP_UPLOAD_FILE_PK", "LINE_NUMBER", "COLUMN_NAME", "ERROR_MESSAGE"
				, "EXCEPTION_MESSAGE");
	}

	public int insert(TempUploadFileError tempUploadFileError) {

		/*
		Map<String, Object> parameters = new HashMap<String, Object>();

		Long tempUploadFileErrorPk = new Long(sequence.nextLongValue());
		parameters.put("TEMP_UPLOAD_FILE_ERROR_PK",  tempUploadFileErrorPk);
		parameters.put("TEMP_UPLOAD_FILE_PK", tempUploadFileError.getTempUploadFile().getTempUploadFilePk() );
		parameters.put("LINE_NUMBER",  tempUploadFileError.getLineNumber());
		parameters.put("COLUMN_NAME", tempUploadFileError.getColumnName());
		parameters.put("ERROR_MESSAGE", tempUploadFileError.getErrorMessage());

		parameters.put("EXCEPTION_MESSAGE",  tempUploadFileError.getExceptionMessage());

		parameters.put("UPDATED_DATE",  tempUploadFileError.getUpdatedDate());
		parameters.put("UPDATED_BY",  tempUploadFileError.getUpdatedBy());
		parameters.put("CREATED_DATE", tempUploadFileError.getCreatedDate());
		parameters.put("CREATED_BY",  tempUploadFileError.getCreatedBy());

		int updateCounts = tempUploadFileErrorJdbcInsert.execute(parameters);		

		if (updateCounts > 0)
			tempUploadFileError.setTempUploadFileErrorPk(tempUploadFileErrorPk);

		return updateCounts;
		 */

		List<TempUploadFileError> tempUploadFileErrors = new ArrayList<TempUploadFileError>();
		tempUploadFileErrors.add(tempUploadFileError);

		return this.insert(tempUploadFileErrors);
	}

	public int insert(List<TempUploadFileError> tempUploadFileErrors) {

		int result = 0;

		if (CollectionUtils.isNotEmpty(tempUploadFileErrors))
		{
			List<SqlParameterSource> params = new ArrayList<SqlParameterSource>(tempUploadFileErrors.size());
			
			for (TempUploadFileError tempUploadFileError: tempUploadFileErrors)
			{
				MapSqlParameterSource parameters = new MapSqlParameterSource();

				Long tempUploadFileErrorPk = new Long(sequence.nextLongValue());				
				parameters.addValue("TEMP_UPLOAD_FILE_ERROR_PK", tempUploadFileErrorPk, Types.NUMERIC);
				parameters.addValue("TEMP_UPLOAD_FILE_PK", tempUploadFileError.getTempUploadFile().getTempUploadFilePk(), Types.NUMERIC);
				parameters.addValue("LINE_NUMBER", tempUploadFileError.getLineNumber(), Types.NUMERIC);
				parameters.addValue("COLUMN_NAME", tempUploadFileError.getColumnName(), Types.VARCHAR);
				parameters.addValue("ERROR_MESSAGE", tempUploadFileError.getErrorMessage(), Types.VARCHAR);
				
				if (null != tempUploadFileError.getExceptionMessage())
				{
					String m = tempUploadFileError.getExceptionMessage();
					byte[] bytes = m.getBytes();
					if (bytes.length > 255)
					{
						logger.info("上傳檔案檢核發生系統錯誤: {}", tempUploadFileError.getExceptionMessage());
						m = new String(bytes, 0, 255);
					}
					parameters.addValue("EXCEPTION_MESSAGE", m, Types.VARCHAR);
				}
				else
					parameters.addValue("EXCEPTION_MESSAGE", (String)null, Types.VARCHAR);

				params.add(parameters);
				tempUploadFileError.setTempUploadFileErrorPk(tempUploadFileErrorPk);
			}

			
			int[] batchCount = tempUploadFileErrorJdbcInsert.executeBatch(params.toArray(new MapSqlParameterSource[0]));
			for(int i: batchCount)
				result = result + i;

		}

		return result;
	}

	public int deleteByTempUploadFilePk(Long tempUploadFilePk) {
		StringBuffer sql = new StringBuffer();
		MapSqlParameterSource parameters = new MapSqlParameterSource();
		
		sql.append("DELETE FROM TEMP_UPLOAD_FILE_ERROR WHERE TEMP_UPLOAD_FILE_PK = :TEMP_UPLOAD_FILE_PK");
		parameters.addValue("TEMP_UPLOAD_FILE_PK", tempUploadFilePk, Types.NUMERIC);
		
		return this.getSimpleJdbcTemplate().update(sql.toString(), parameters);
	}

	public PaginatedList<TempUploadFileError> queryPaginatedListByTempUploadFilePk(
			Long tempUploadFilePk,
			PaginatedList<TempUploadFileError> paginatedList) {
		SqlQueryProvider sqlQueryProvider = this.getSqlQueryProviderByUploadFilePk(tempUploadFilePk, paginatedList);
		return this.queryForPaginatedList(sqlQueryProvider, new TempUploadFileErrorRowMapper(), paginatedList.getPageNumber(), paginatedList.getPageSize());
	}
	
	protected SqlQueryProvider getSqlQueryProviderByUploadFilePk(Long tempUploadFilePk,
			PaginatedList<TempUploadFileError> paginatedList)
	{

		/* 查詢 SQL */
		StringBuffer sql = new StringBuffer();

		/* 查詢條件 */
		List<Object> args = new ArrayList<Object>();
		
		sql.append("SELECT * FROM TEMP_UPLOAD_FILE_ERROR WHERE TEMP_UPLOAD_FILE_PK = ?");
		args.add(tempUploadFilePk);
		
		if (null != paginatedList)
		{
			if (StringUtils.isNotEmpty(paginatedList.getSortCriterion()))
			{
				sql.append(" ORDER BY ").append(paginatedList.getSortCriterion()).append(" ").append( 2==paginatedList.getSortDirection() ? "ASC" : "DESC" );
			}			
		}
		SqlQueryProvider sqlQueryProvider = new SqlQueryProvider(sql.toString(), args);
		return sqlQueryProvider;
	}

}
